import urllib.request
import uuid
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
from selenium.common.exceptions import TimeoutException, NoSuchElementException  # 还有更多的异常可以用
import time
import datetime
from PIL import Image
import os
import imgutil
import pytesseract
from apscheduler.schedulers.background import BackgroundScheduler

# Chrome 的无界面模式
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--window-size=1920,1080')
chrome_options.add_argument('--start-maximized')
browser = webdriver.Chrome(chrome_options=chrome_options)

u_djh = 'djh220628'
pwd_djh = 'djh@883228'


def rest(sec):
    time.sleep(sec)


def crack_code(url):
    """下载验证码图片
    :returns: 返回验证码图片

    """

    image_path = 'codes/' + str(uuid.uuid1()) + '.png'
    # 先存到本地
    urllib.request.urlretrieve(url, image_path)
    imgcode = Image.open(image_path)
    # 处理图片
    parsed_img = imgutil.img_color_enhance(imgcode)[0]
    #  parsed_img.show()
    result = pytesseract.image_to_string(
        parsed_img, config='--psm 7 digit 1234567890')
    print(result)
    return result


def login(index_url, u_user, pwd_user):
    """登录

    :index_url: 登录 url
    :returns: 1 失败, 重新登录

    """
    try:
        wait = None
        browser.get(index_url)
        wait = WebDriverWait(browser, 10)
        wait.until(EC.presence_of_element_located((By.ID, 'cimage_portal')))
        # 破解验证码
        e_code = browser.find_element_by_id('cimage_portal')
        code_url = e_code.get_attribute('src')
        code = crack_code(code_url)
        left_num = 0
        right_num = 0
        code_num = 0
        if '+' in code:
            nums = code.split('+')
            left_num = (int)(nums[0].strip())
            right_num = (int)(nums[1].replace(
                '=', '').replace('?', '').strip())
            code_num = left_num + right_num
        else:
            print('验证码识别失败!')
            return 1
        # 填写登录表单
        rest(1)
        e_input_code = browser.find_element_by_id('valCode1')
        e_input_code.clear()
        print('计算验证码的值为: ' + str(code_num))
        e_input_code.send_keys(str(code_num))
        #  actions = ActionChains(driver).move_to_element(e_input_code)
        #  driver.execute_script('document.getElementById("logonmobile1").value="13888888888"')
        e_username = browser.find_element_by_id('info_username-1')
        e_password = browser.find_element_by_id('info_password-1')
        rest(1)
        e_username.clear()
        e_username.send_keys(u_user)
        rest(1)
        e_password.clear()
        e_password.send_keys(pwd_user)
        # 点击登录
        rest(1)
        e_login_btn = browser.find_element_by_id('loginyc')
        print(browser.current_url)
        e_login_btn.click()
        wait = WebDriverWait(browser, 10)
        wait.until(EC.presence_of_element_located(
            (By.XPATH, '//div[@class="midInfo"]')))
        print(browser.current_url)
        return 0
    except TimeoutException as e:
        raise e
        print('超时异常, 登录失败!')
        return 1
    except NoSuchElementException as e:
        raise e
        print('找不到指定的元素!')
        return 1


def service():
    """查看信息, 做一些增加经验的事情
    :returns: None

    """
    # username
    #  e_user = browser.find_element_by_xpath('//div[@class="g_header"]//a[@class="userFace f1"]')
    e_user = browser.find_element_by_xpath(
        '/html/body/div[1]/div/div[1]/div/a')
    user = e_user.get_attribute('title')
    print(user)
    #  e_class = browser.find_element_by_xpath('//div[@class="g_header"]//dl[@class="fl classRoom"]/dd/a')
    #  cls = e_class.text
    #  print(cls)
    print('登录成功 ' + user)
    wait = WebDriverWait(browser, 10)
    wait.until(EC.presence_of_element_located(
        (By.XPATH, '//div[@class="midInfo"]')))
    rank = browser.find_element_by_xpath(
        '//div[@class="midInfo"]/div/p[2]').text
    rank = rank.split(' ')[0]
    print('目前全省排名: ' + rank)
    # 学科基地校
    e_xkjdx = browser.find_element_by_partial_link_text('学科基地校')
    xkjdx_url = e_xkjdx.get_attribute('href')
    last_handler = browser.current_window_handle
    # js 的 window.open() 方式打开新标签页
    #  browser.execute_script('window.open()')
    print('当前的 handler 是 ' + last_handler)
    rest(2)
    e_xkjdx.click()
    print('已成功访问 学科基地校')
    current_handler = browser.current_window_handle
    print('当前的 handler 是 ' + current_handler)
    browser.switch_to.window(browser.window_handles[1])
    print('关闭 学科基地校 标签页')
    rest(2)
    rest(2)
    browser.switch_to.window(last_handler)
    print('回到上一个标签页')
    rest(2)


def main(user, pwd):
    """主函数
    :returns: None

    """
    index_url = 'http://yun.zjer.cn/index.php'
    while True:
        result = login(index_url, user, pwd)
        if result == 0:
            break
    service()

    print('退出浏览器!')
    browser.close()
    browser.quit()


def djh_task():
    """丁洁虹任务
    :returns: None

    """
    main(u_djh, pwd_djh)
    print(u_djh, "任务完成!", datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S"))


if __name__ == "__main__":
    # 创建后台执行的 schedulers
    scheduler = BackgroundScheduler()
    # 添加调度任务
    # 触发器选择 cron
    scheduler.add_job(djh_task, 'cron', day_of_week='0-6',
                      hour='8', minute='11')
    # 启动调度任务
    scheduler.start()
    while True:
        rest(5)
